package com.wing.common.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.dao.ContractChangeRecordDao;
import com.wing.common.exception.BusinessException;
import com.wing.common.model.entity.Contract;
import com.wing.common.model.entity.ContractChangeRecord;
import com.wing.common.model.request.ContractChangeRecordForm;
import com.wing.common.model.response.ContractChangeRecordVO;
import com.wing.common.utils.LocalDateTimeUtils;
import com.wing.contract.model.entity.ContractCategory;
import com.wing.sell.model.entity.Agent;
import com.wing.sell.model.entity.CustomersInfo;
import com.wing.sell.service.AgentService;
import com.wing.sell.service.CustomersInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 合同变更记录-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class ContractChangeRecordServiceImpl extends ServiceImpl<ContractChangeRecordDao, ContractChangeRecord> implements ContractChangeRecordService {

    @Autowired
    private AgentService agentService;
    @Autowired
    private CustomersInfoService customersInfoService;

    @Override
    @Transactional(readOnly = false)
    public int add(ContractChangeRecordForm contractChangeRecordForm) {

        //校验

        ContractChangeRecord contractChangeRecord =new ContractChangeRecord();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(ContractChangeRecord.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(contractChangeRecordForm, contractChangeRecord, copyOptions);

        // 判断是否选择最终版
        if(contractChangeRecord.getIsFinal()){
            contractChangeRecord.setStatus(ContractChangeRecord.Status.hasSign);
        }
        int i = baseMapper.insert(contractChangeRecord);
        if(i > 0){
            // 判断是否选择最终版
            if(contractChangeRecord.getIsFinal()){
                // 修改合同状态
                baseMapper.updateContractStatus(contractChangeRecord.getContactsId());

                // 修改其他合同变更记录状态
                updateOtherContractStatus(contractChangeRecord);

                // 修改代理商类型、状态
                updateAgent(contractChangeRecord);
            }
        }
        return i;
    }

    @Override
    public List<ContractChangeRecordVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<ContractChangeRecordVO> pageList4app(Page page, Map<String, Object> params) {
        List<ContractChangeRecordVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public ContractChangeRecordVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional(readOnly=false)
    public boolean setContractFinal(Long id, String deliveryTime, String address, Long keeper) {
        ContractChangeRecord contractChangeRecord = baseMapper.selectById(id);
        if(null == contractChangeRecord){
            throw new BusinessException(300, "参数错误");
        }
        contractChangeRecord.setStatus(ContractChangeRecord.Status.hasSign);
        contractChangeRecord.setDeliveryTime(LocalDateTimeUtils.convertStringToLDT(deliveryTime, "yyyy-MM-dd HH:mm:ss"));
        contractChangeRecord.setAddress(address);
        contractChangeRecord.setKeeper(keeper);
        int i = baseMapper.updateById(contractChangeRecord);
        if(i > 0){
            // 修改合同状态
            baseMapper.updateContractStatus(contractChangeRecord.getContractId());

            // 修改其他合同变更记录状态
            updateOtherContractStatus(contractChangeRecord);

            // 修改代理商类型、状态
            updateAgent(contractChangeRecord);
        }
        return i > 0;
    }

    public void updateOtherContractStatus(ContractChangeRecord contractChangeRecord){
        ContractChangeRecord record = new ContractChangeRecord();
        record.setStatus(ContractChangeRecord.Status.hasDiscard);
        update(record, new QueryWrapper<ContractChangeRecord>().eq("contract_id", contractChangeRecord.getContractId()).ne("id", contractChangeRecord.getId()));
    }

    public void updateAgent(ContractChangeRecord contractChangeRecord){
        // 获取合同数据
        Contract contract = baseMapper.getContract(contractChangeRecord.getContractId());

        // 修改代理商类型、状态
        if(contract.getType().equals(ContractCategory.Type.channel)){
            Agent agent = agentService.getById(contract.getSubjectId());
            agent.setType(Agent.Type.on);
            agent.setStatus(Agent.Status.complet);
            agentService.updateById(agent);
        }
        //销售订单页面添加订单 显示的都是意向客户和正式客户   如果客户是意向客户，合同设置为终版后，客户修改为正式客户
        if(contract.getType().equals(ContractCategory.Type.client)){
            CustomersInfo customersInfo = customersInfoService.getById(contract.getSubjectId());
            if (customersInfo.getCustomerType().equals(CustomersInfo.CustomerType.Intended)){
                customersInfo.setCustomerType(CustomersInfo.CustomerType.formal);
                customersInfoService.updateById(customersInfo);
            }
        }
    }

}
